package com.lagou;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author godai
 * @date 2021/1/31 13:21
 * @description
 */
public class RpcDecoder extends ByteToMessageDecoder {
    private Class<?> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() > 0) {
            int classNameLength = in.readInt();
            int classDataLenght = in.readInt();

            byte[] classNameByte = new byte[classNameLength];
            byte[] classDataByte = new byte[classDataLenght];
            in.readBytes(classNameByte);
            in.readBytes(classDataByte);

            String s = new String(classNameByte);
            Class<?> aClass = Class.forName(s);
            out.add(serializer.deserialize(aClass, classDataByte));
        }
    }

}


